<?php
/**
 * Created by PhpStorm.
 * User: fantaixi
 * Date: 2018/11/4
 * Time: 16:59
 */

namespace app\api\controller;


use app\common\wx_common;
use app\common\WXBizDataCrypt;
use think\Controller;
use think\Db;

class Login extends Base
{
    public function __construct()
    {
        parent::__construct();

    }

    public function index()
    {

    }

    public function getMiniToken()
    {
        $code = input('code');
        $str = input('data');
        $iv = input('iv');
        if (!$code || !$str || !$iv) {
            return $this->errorReturn(100, 'code或data或iv不存在');
        }

        if (!env('API_LOGIN_DEMO', false)) {
            $back = wx_common::getInstance()->wx_miniprogram_login($code);
            //处理登陆错误

            if (isset($back['errcode'])) {

                return $this->errorReturn(101, 'code已失效');
            }
            $pc = new WXBizDataCrypt($this->wechat['mini_app_id'], $back['session_key']);
            $errCode = $pc->decryptData($str, $iv, $userInfo );
            if($errCode){
                trace("mini_iv:".$iv,'error');
                trace("mini:error".$errCode,'error');
                return $this->errorReturn(200,'服务器忙，请稍后再试');
            }
            $userInfo = json_decode($userInfo,1);

        } else {
            $a = Db::name('member')->find(1);
            $userInfo['openid'] = $a['mini_openid'];
            $userInfo['unionid'] = $a['wx_unionid'];
        }

        $token = getToken();
        $expire = 7 * 24 * 3600;
        $user = Db::name('member')->where('mini_openid', $userInfo['openId'])->whereOr('wx_unionid', $userInfo['unionId'])->find();
        if ($user) {
            $user['type'] = 2;
            if(!$user['mini_openid']){
                //小程序注册的号，H5登陆补充资料
                $update = [
                    'mini_openid' => $userInfo['openId'] ?? '',
                    'modtime' => time(),
                ];
                Db::name('member')->where('id',$user['id'])->update($update);
            }
            cache($token, $user, $expire);
            return $this->successReturn(['token' => $token, 'user_id' => $user['id']]);
        }

        $user = $this->register($userInfo, 2);

        if ($user['id']) {

            $user['type'] = 2;
            cache($token, $user, $expire);
            return $this->successReturn(['token' => $token, 'user_id' => $user['id']]);
        } else {
            return $this->errorReturn(300, '操作失败');
        }
    }

    public function getH5Token()
    {
        $code = input('code');
        if (!$code) {
            return $this->errorReturn(100, 'code不存在');
        }

        if (!env('API_LOGIN_DEMO', false)) {
            $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->wechat['app_id'].'&secret='.$this->wechat['secret'].'&code='.$code.'&grant_type=authorization_code';
            $res1 = creat_curl($get_token_url);
            $userInfo = json_decode($res1,true);
            //处理登陆错误
            if (!$userInfo || isset($userInfo['errcode'])) {
                return $this->errorReturn(101, 'code已失效');
            }
        } else {
            $a = Db::name('member')->find(1);
            $userInfo['openid'] = $a['wx_openid'];
            $userInfo['unionid'] = $a['wx_unionid'];
        }

        //查看数据库用户是否注册
        $user = Db::name('member')->where('wx_openid',$userInfo['openid'])->whereOr('wx_unionid', $userInfo['unionid'])->find();

        $token = getToken();
        $expire = 7 * 24 * 3600;
        if ($user) {
            $user['type'] = 1;
            if(!$user['wx_openid']){
                //小程序注册的号，H5登陆补充资料
                $user1 = $this->get_user_info($userInfo['access_token']);
                $update = [
//                    'nickname' => isset($user1['nickname']) ?filterEmoji($user1['nickname']):'',
//                    'head_img' => $user1['headimgurl'] ?? '',
//                    'sex' => $user1['sex'] ?? '',
//                    'province' => $user1['province'] ?? '',
//                    'country' => $user1['country'] ?? '',
//                    'city' => $user1['city'] ?? '',
                    'wx_openid' => $user1['openid'] ?? '',
                    'modtime' => time(),
                ];
                Db::name('member')->where('id',$user['id'])->update($update);
            }
            cache($token, $user, $expire);
            return $this->successReturn(['token' => $token, 'user_id' => $user['id']]);
        }
        $user1 = $this->get_user_info($userInfo['access_token']);

        $user = $this->register($user1, 1);

        if ($user) {
            $user['type'] = 1;
            cache($token, $user, $expire);
            return $this->successReturn(['token' => $token, 'user_id' => $user['id']]);
        } else {
            return $this->errorReturn(300, '操作失败');
        }
    }

    /**
     * @param $userInfo
     * @param $type 1为公众号，2为小程序
     */
    public function register($userInfo, $type)
    {
        if($type == 1){
            //H5
            $user = [
                'nickname' => isset($userInfo['nickname']) ?filterEmoji($userInfo['nickname']):'',
                'status' => 1,
                'total' => 0,
                'tel' => '',
                'head_img' => $userInfo['headimgurl'] ?? '',
                'sex' => $userInfo['sex'] ?? '',
                'province' => $userInfo['province'] ?? '',
                'country' => $userInfo['country'] ?? '',
                'city' => $userInfo['city'] ?? '',
                'wx_openid' =>  $userInfo['openid'] ?? '',
                'mini_openid' => '',
                'wx_unionid' =>  $userInfo['unionid'] ?? '',
                'log_time' => time(),
                'addtime' => time(),
                'modtime' => time(),
            ];
        }else{
            //小程序
            $user = [
                'nickname' => isset($userInfo['nickName']) ?filterEmoji($userInfo['nickName']):'',
                'status' => 1,
                'total' => 0,
                'tel' => '',
                'head_img' => $userInfo['avatarUrl'] ?? '',
                'sex' => $userInfo['sex'] ?? '',
                'province' => $userInfo['province'] ?? '',
                'country' => $userInfo['country'] ?? '',
                'city' => $userInfo['city'] ?? '',
                'wx_openid' => '',
                'mini_openid' =>  $userInfo['openId'] ,
                'wx_unionid' => isset($userInfo['unionId']) ? $userInfo['unionId'] : '',
                'log_time' => time(),
                'addtime' => time(),
                'modtime' => time(),
            ];
        }


        $userId = Db::name('member')->insertGetId($user);
        $user['id'] = $userId;
        return $user;
    }

    /**
     * @param $data
     * H5接口拉取用户基本信息
     */
    protected function get_user_info($access_token)
    {
        $url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $this->wechat['app_id'] . '&lang=zh_CN';
        $res = creat_curl($url);
        $res = json_decode($res, true);
        return $res;
    }


}